import random
import sys
from collections import deque

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def generate_random_tree(n, min_val, max_val):
    if n == 0:
        return None
    nodes = [TreeNode(random.randint(min_val, max_val)) for _ in range(n)]
    root = nodes[0]
    queue = deque([root])
    i = 1
    while queue and i < n:
        current = queue.popleft()
        if i < n:
            current.left = nodes[i]
            queue.append(nodes[i])
            i += 1
        if i < n:
            current.right = nodes[i]
            queue.append(nodes[i])
            i += 1
    return root

def serialize(root):
    if not root:
        return []
    result = []
    queue = deque([root])
    while queue:
        node = queue.popleft()
        if node:
            result.append(node.val)
            queue.append(node.left)
            queue.append(node.right)
        else:
            result.append(None)
    # 移除末尾的None
    while result and result[-1] is None:
        result.pop()
    return result

if __name__ == "__main__":
    n = int(sys.argv[1]) if len(sys.argv) > 1 else 10
    min_val = int(sys.argv[2]) if len(sys.argv) > 2 else -100
    max_val = int(sys.argv[3]) if len(sys.argv) > 3 else 100
    target = int(sys.argv[4]) if len(sys.argv) > 4 else 0
    root = generate_random_tree(n, min_val, max_val)
    serialized = serialize(root)
    print(f"Tree: {serialized}")
    print(f"Target Sum: {target}")    